package com.dce.blockchain.web.util;
import java.security.MessageDigest;
import java.util.UUID;
import org.springframework.util.DigestUtils;
/**
密码学工具类
*
*/
public class CryptoUtil {
/**
SHA256散列函数
@param str
@return
*/
  //计算SHA256哈希值
public static String SHA256(String str) {
	MessageDigest messageDigest;
	String encodeStr = "";
	try {
		messageDigest = MessageDigest.getInstance("SHA-256");
		messageDigest.update(str.getBytes("UTF-8"));
		encodeStr = byte2Hex(messageDigest.digest());
		} catch (Exception e) {
						System.out.println("getSHA256 is error" + e.getMessage());
		}
		return encodeStr;
	}
  //二进制转字符串
	private static String byte2Hex(byte[] bytes) {
		StringBuilder builder = new StringBuilder();
		String temp;
		for (int i = 0; i < bytes.length; i++) {
			temp = Integer.toHexString(bytes[i] & 0xFF);
			if (temp.length() == 1) {
					builder.append("0");
			}
			builder.append(temp);
		}
		return builder.toString();
	}
  //字符串MD5加密
	public static String MD5(String str) {
		String resultStr = DigestUtils.md5DigestAsHex(str.getBytes());
		return resultStr.substring(4, resultStr.length());
	}
  //随机生成不重复的ID
	public static String UUID() {
		return UUID.randomUUID().toString().replaceAll("", "");
	}
}